package com.ytjj.qmyx.admin.listener;

import com.ytjj.common.constants.RedisConstants;
import com.ytjj.qmyx.admin.mapper.ReportsMapper;
import org.redisson.api.listener.MessageListener;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RedisEventMessageListener extends KeyExpirationEventMessageListener {

    @Resource
    private ReportsMapper reportsMapper;

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisEventMessageListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    protected void doHandleMessage(Message message) {
        // 这个就是过期的key ，过期后，也就是事件触发后对应的value是拿不到的。
        // 这里实现业务逻辑，如果是服务器集群的话需要使用分布式锁进行抢占执行。
        String key = message.toString();
        // 剔除字符串中的数字
        String replaceAll = key.replaceAll("\\d+", "");

        if (RedisConstants.NO_CHAT_KEY.equals(replaceAll)){
            // 取出字符串中的数字
            String regEx = "[^0-9]";
            Pattern compile = Pattern.compile(regEx);
            Matcher matcher = compile.matcher(key);
            String trim = matcher.replaceAll("").trim();
            int parseInt = Integer.parseInt(trim);
            reportsMapper.timedTask(parseInt);
//        System.out.println("key = " + key);
//        System.out.println("end = " + LocalDateTime.now());
        }
    }

//    @Scheduled(cron = "0 0/3 * * * ?")
//    @Async
//    public void testTimedTask() {
//        System.out.println("当前时间 = " + LocalDateTime.now());
//    }

}
